from django.shortcuts import render
from django.views import View
from apps.areas.models import Area
from django import http
from django.core.cache import cache

# Create your views here.


class ProvinceAreasView(View):
    """查询省份数据"""
    def get(self, request):
        # 读取缓存数据
        province_dict_list = cache.get('province_list')
        if province_dict_list:
            return http.JsonResponse({'code': 0, 'errmsg': 'OK', "province_list": province_dict_list})

        # 查询省份数据
        province_model_list = Area.objects.filter(parent=None)

        # 将查询集列表转换成字典列表
        province_dict_list = []
        for province_model in province_model_list:
            # 模型类型数据转成字典数据
            province_dict = {
                "id": province_model.id,
                "name": province_model.name,
            }
            province_dict_list.append(province_dict)

        # 缓存省份字典列表
        cache.set('province_list', province_dict_list, 3600)

        # JsonResponse()不是别模型数据(模型对象和查询集),只识别字典\列表\字典列表\
        # 响应结果
        return http.JsonResponse({'code': 0, 'errmsg': 'OK', "province_list": province_dict_list})


class SubAreasView(View):
    """查询城市或者区县"""
    def get(self, request, parent_id):
        # 读取缓存数据
        sub_data = cache.get("sub_data_%s" % parent_id)
        if sub_data:
            return http.JsonResponse({'code': 0, 'errmsg': 'OK', "sub_data": sub_data})

        # 查询当前父级地区:get()
        parent_area = Area.objects.get(id=parent_id)
        # 查询父级地区的所有子级:all()
        sub_model_list = parent_area.subs.all()

        # 子级模型列表转字典列表
        subs = []
        for sub_model in sub_model_list:
            sub_dict = {
                "id": sub_model.id,
                "name": sub_model.name,
            }
            subs.append(sub_dict)

        sub_data = {
            "id": parent_area.id,
            "name": parent_area.name,
            "subs": subs,
        }

        # 缓存子级数据(市和区县)
        cache.set('sub_data_%s' % parent_id, sub_data, 3600)

        # 响应数据
        return http.JsonResponse({'code': 0, 'errmsg': 'OK', "sub_data": sub_data})


